package buildrobot_info

import (
	"go_server/game_server/api/service/build"
	"go_server/game_server/protocol/pb"
	"go_server/zinx/ziface"
	"go_server/zinx/zlog"
)

func (s *Buildrobot_info_service) S2C_AddBuildRobotLvUp(conn ziface.IConnection, roleid int64, msg *pb.AddRobot2BuildLvUpC2S) pb.ErrorCodeManager {
	robot := s.LoadByRoleId(roleid)
	isAnyBuildUpgradeSuc := false
	if robot != nil {
		build_info_id := build.CombinBuildKey(roleid, msg.Buildmapid, msg.Buildcfgid, msg.Buildserid)

		if !build.TestBuildCanLevelUp(build_info_id) {
			return pb.ErrorCodeManager_BUILDROBOTINFO_NOT_RESENOUGH
		}

		//if build.CheckdBuildConsumeStatus(build_info_id) {
		if code, ok := robot.CheckUpgradeEnough(build_info_id); ok {
			msgS2C := &pb.AddRobot2BuildLvUpS2C{}
			//加入建造中的建筑
			bv := &Cache_buildrobot_info_build_data{}
			if bd, ok := robot.BuildData[build_info_id]; ok { //如果要加入的建筑已在建造中
				bv = bd
			} else {
				robot.BuildData[build_info_id] = bv
			}
			bv.SetBuild_info_id(build_info_id)

			modifyBuilds := make([]*Cache_buildrobot_info_build_data, 0) //有变更的建筑
			if newrids, add := bv.AddRobot(msg.Robotserids, robot.GetRobotBySerid); add {
				//有新机器人加入建造队列
				if len(newrids) > 0 { //新加入建造的机器人
					for i := 0; i < len(newrids); i++ {
						if r, ok := robot.RobotData[newrids[i]]; ok {
							r.Trans2Work()
						}
					}
				}
				modifyBuilds = append(modifyBuilds, bv)
			}

			if robot.BuildData != nil {
				for bid, bv := range robot.BuildData {
					if bid != build_info_id {
						if _, remove := bv.RemoveRobot(msg.Robotserids, robot.GetRobotBySerid); remove {
							//机器人有变动
							modifyBuilds = append(modifyBuilds, bv)
						}
					}
				}
			}

			if len(modifyBuilds) > 0 {
				msgS2C.IdleRobots = robot.Pb_GetIdleRobot()
				msgS2C.Builds = make([]*pb.BuildRobotLvUpData, 0)
				for i := 0; i < len(modifyBuilds); i++ {
					bv := modifyBuilds[i]
					if bv.CalculateUpgradeTime(robot.TransVolume, robot.GetRobotBySerid, false) {
						isAnyBuildUpgradeSuc = true
					}
					pbd := bv.ToPb_BuildRobotLvUpData(robot.GetRobotBySerid)
					msgS2C.Builds = append(msgS2C.Builds, pbd)
				}
			}

			build.DeductBuildLevelConsume(bv.Build_info_id)

			if isAnyBuildUpgradeSuc {
				Buildrobot_info_serviceObj.S2C_BuildRobotUpgradeSuc(conn, robot)
			}

			defer robot.Save_AllData()

			if msgS2C != nil {
				zlog.Debugf("ProtocolManager_AddBuildRobotLvUp %v", msgS2C)
				defer func() {
					conn.SendBuffPBMsg(uint32(pb.ProtocolManager_AddBuildRobotLvUp), msgS2C)
				}()
			}
		} else {
			return code
		}
		/*} else {
			return constants.BUILDROBOTINFO_NOT_UP2BUILDING
		}*/
	}
	return pb.ErrorCodeManager_SUCCESS
}
